package com.dynamic.mybatis.web.controller;

import com.dynamic.mybatis.core.session.DynamicSqlSessionTemplate;
import com.dynamic.mybatis.core.utils.FileUtils;
import com.dynamic.mybatis.generator.GeneratorHelp;
import com.dynamic.mybatis.generator.vo.GeneratorVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/generator/")
public class GeneratorController {

    @Autowired
    private DynamicSqlSessionTemplate sqlSessionTemplate;

    @PostMapping("generate")
    public void generate(@RequestBody GeneratorVo generatorVo, HttpServletResponse response) {

        DataSource dataSource = sqlSessionTemplate.getDataSource(generatorVo.getDataSource().getDataSourceCode());
        generatorVo.getDataSource().setDataSource(dataSource);
        generatorVo.setOpen(Boolean.FALSE);
        String zip = GeneratorHelp.generate(generatorVo);
        File file = new File(zip);
        int size;
        try (OutputStream os = response.getOutputStream();
             FileInputStream fis = new FileInputStream(file);) {
            size = fis.available();
            response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Length", "" + size);
            int i;
            while ((i = fis.read()) != -1) {
                os.write(i);
            }
            os.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            FileUtils.delete(zip.substring(0, zip.lastIndexOf(".")), zip);
        }
    }
}
